<?php

namespace XWAM\Model;

/**
 * DocumentModel 类
 *
 * @since 1.0 <2015-10-22> SoChishun <14507247@qq.com> Added.
 */
class DocumentModel extends AppbaseModel {

    protected $tableName = 't_porg_document';

    /**
     * 获取文档
     * @param int $id 文档编号
     * @param boolean $decode 是否对内容执行html_entity_decode
     * @return array
     * @since 1.0 2016-6-15 SoChishun Added.
     */
    function find_document($id, $decode = true) {
        $data = $this->find($id);
        if ($data) {
            $data['content'] = $this->table('t_porg_document_content')->where(array('document_id' => $id))->getField('content');
            if ($decode && !empty($data['content'])) {
                $data['content'] = html_entity_decode($data['content']);
            }
        }
        return $data;
    }

    function save_document() {
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('category_id', 'number', '类别无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        //图片上传
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Document/', 'skipEmpty' => true));
        if (is_array($msg) && isset($msg['picture_url'])) {
            $this->data['picture_url'] = $msg['picture_url']['filepath'];
        }
        if (isset($this->data['create_time']) && empty($this->data['create_time'])) {
            unset($this->data['create_time']);
        }
        $content = $this->data['content'];
        unset($this->data['content']);
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
            if (false !== $result) {
                $this->table('t_porg_document_content')->add(array('document_id' => $result, 'content' => $content));
            }
        } else {
            $id = $this->id;
            $result = $this->save();
            if (false !== $result) {
                $this->table('t_porg_document_content')->where(array('document_id' => $id))->setField(array('content' => $content));
            }
        }
        return $this->returnMsg($result);
    }

    function change_status($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function change_sort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    function delete_document($id) {
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

}
